import tkinter
from tkinter import filedialog
from tkinter import messagebox
import threading
import socket
import time
import os
import configparser as cp
import base64
class A:
    def __init__(self,root):
        self.udp_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.udp_client.bind(('', 8081))
        self.address = ('169.254.247.196', 8080)
        root.geometry('400x500')
        self.s = tkinter.StringVar()
        self.s_1 = tkinter.Scrollbar(root)
        self.s_1.pack(side=tkinter.RIGHT, fill=tkinter.Y)
        self.T = tkinter.Text(root, width=50,yscrollcommand=self.s_1.set)
        self.T.place(x=20, y=20)
        self.T_2 = tkinter.Text(root, width=36, heigh=5)
        self.T_2.place(x=20, y=400)
        self.B = tkinter.Button(root, text='发送', command=self.send)
        self.B.place(x=295, y=400, width=80, heigh=35)
        self.B = tkinter.Button(root, text='保存聊天记录', command=self.save)
        self.B.place(x=295, y=440, width=80, heigh=35)
        self.B = tkinter.Button(root, text='撤回', command=self.withdraw)
        self.B.place(x=295, y=360, width=80, heigh=35)
        self.s_1.config(command=self.T.yview)
        self.filename = ".\config.ini"
        self.i = cp.ConfigParser()
        self.i.read(self.filename, 'utf-8')

    def withdraw(self):
        pass


    def save(self):
        mess = self.T.get('0.0','end')
        o = os.path.expanduser(r'C:\Users\Administrator\Desktop')
        file = filedialog.asksaveasfilename(title='选择文件',filetypes=[('文本','txt')],
                                            initialfile='udp聊天记录',initialdir=o)
        if file:
            file += '.txt'
            try:
                with open(file, 'r', encoding='utf-8')as book:
                    m = book.read()
                if m:
                    t = tkinter.messagebox.askyesno(title='注意',message='文件已存在，确定覆盖吗')
                    if t:
                        with open(file,'w',encoding='utf-8') as book:
                            book.write(mess)
                            tkinter.messagebox.showinfo(message='保存成功')
            except:
                with open(file, 'w', encoding='utf-8') as book:
                    book.write(mess)
                    tkinter.messagebox.showinfo(title='保存成功')

    def send(self):
        while True:
            mess = self.T_2.get('0.0', 'end')
            if mess:
                self.udp_client.sendto(str(mess).encode('utf-8'),self.address)
                t = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
                self.T.insert('end', t + ' 我：'+'\n''%s' % mess,'tag')
                self.T.tag_add('tag','end')
                self.T.tag_config('tag', foreground=self.i.get('FONT_COLOR', 'other'))
                self.T_2.delete('0.0', 'end')
                break

    def recv(self):
        while True:
            data = self.udp_client.recvfrom(1024)
            t2 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            if data[0]:
                a = self.T.insert('end', t2 + ' 对方：' + '\n''%s' % data[0].decode('utf-8') + '\n', 'a')
                self.T.tag_add('a','end')
                self.T.tag_config('a', foreground=self.i.get('FONT_COLOR', 'myself'))
                time.sleep(0.1)

    def main(self):
        t2 = threading.Thread(target=self.recv)
        t2.start()

if __name__ == '__main__':
    root = tkinter.Tk()
    app = A(root)
    app.main()
    root.mainloop()